<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\User;
use App\Models\Syslog;
use App\Tool\SMS\SmsSubmail;
class UserController extends Controller
{
//    public function __construct()
//    {
//        if (auth()->user()==""){return redirect('LogOut');}
//    }
    /*
     * 退出
     */
    public function logout(Request $request)
    {
        $cookie_key =  array_keys($_COOKIE);
        for ($i = 0;$i<count($cookie_key);$i++){
            $key = $cookie_key[$i];
            if (strchr($key,"remember")){setcookie($key);}
        }
//        $request->session()->invalidate();
        $request->session()->flush();
        return redirect(route('Login'));
    }
    /*
     * 登录
     */
//    public function login(SmsSubmail $smsSubmail)
    public function login()
    {

//        var_dump(auth()->user());
        if(is_object(auth()->user())){return redirect(route('Welcome'));}
        return view('user.login');
    }
    /*
     * 自定义登录数据验证
     */
    public function login_store(Request $request)
    {
//        echo $request->password;exit;
        $this->validate($request,[
            'username' => 'alpha_num|required',
            'password' => 'required|min:6',
            'captcha' => 'required|captcha'
        ],[
            'captcha.required' => '请填写验证码',
            'captcha.captcha' => '验证码错误',
        ]);
        $udata['username'] = $request->username;
        $udata['password'] = $request->password;
        $loginTF = Auth::attempt($udata,$request->remember);
        if ($loginTF){
            return redirect(route('Welcome'));
        }else{
            session()->flash('danger', '账号或密码错误！');
            return back();
        }
    }


    /*
     * 注册用户
     */
    public function register()
    {
//        var_dump(auth()->user());
//        if(is_object(auth()->user())){return redirect(route('Welcome'));}
        return view('user.register');
    }
    /*
     * 验证并注册用户
     */
    public function register_store(Request $request){
        if ($request->isMethod('POST')){

            /**
             * 以下是需要手机验证的代码  （流程3）
             * 当系统需要用户手机认证的时候，可执行如下代码，跳转至二次手机验证注册页面
             * 此段代码需结合register_store_mobile方法使用
             * register_store_mobile提交表单回到本方法，判断来路数据与session数据一致，即写入用户数据
             */
            if (session()->has('code') and session('username')==$request->username and session('email')==$request->email and session('mobile')==$request->mobile){

                $this->validate($request,[
                    'username' => 'required|unique:users|min:5',
                    'email' => 'required|unique:users|email',
                    'mobile' => 'required|min:11|unique:users|mobile',
                    'captcha' => 'required|captcha'
                ]);

                if (session('code')==$request->smscode){
//                    echo $request->mobile;
                    User::create([
                        'username' => $request->username,
                        'email' => $request->email,
                        'mobile' => $request->mobile,
                        'password' => Hash::make($request->password),
                    ]);
                    $request->session()->flush();
                    //模拟登陆
                    $udata['username'] = $request->username;
                    $udata['password'] = $request->password;
                    Auth::attempt($udata);
                    return redirect(route('Welcome'));
                }
                session()->flash('danger', '手机验证码错误！');
                return back();
            }

            /**
             * 以下是需要手机验证的代码  （当前：流程1）
             */
            $data = $this->validate($request,[
                'username' => 'required|unique:users|min:5',
                'email' => 'required|unique:users|email',
                'mobile' => 'required|min:11|unique:users|mobile',
                'password' => 'required|min:6'
            ]);
            session()->put('username', $data['username']);
            session()->put('email', $data['email']);
            session()->put('mobile', $data['mobile']);
            session()->put('password', $data['password']);
            return redirect(route('RegisterToMobile'));


            /**
             * 以下是在无需手机验证下使用的代码。
             * 当用户填入用户名、邮箱、和密码符合validate判断规则后直接注册用户并自动登录
             */
            /*

            User::create([
                'username' => $request->username,
                'email' => $request->email,
                'password' => Hash::make($request->password),
            ]);
            //模拟登陆
            Auth::attempt($data);
            return redirect(route('Welcome'));

            */
        }
    }

    /**
     * 以下是获取手机验证码，之后提交至register_store的 流程3  （当前：流程2）
     */
    public function register_store_mobile()
    {
        /**
         * 只有Session中用户名、邮箱、手机、密码都存在的时候才能加载视图，进行获取短信验证码的操作
         */
        if (session()->has('username') and session()->has('email') and session()->has('mobile') and session()->has('password')){
            return view('user.register_store_mobile');
        }else{
            return redirect(route('Login'));
        }
    }
    //发送注册短信 验证短信
    public function register_to_mobile(Request $request,SmsSubmail $smsSubmail)
    {
        if ($request->isMethod('PUT'))
        {
            if (session()->has('username') and session()->has('email') and session()->has('mobile') and session()->has('password')){

                $syslog = Syslog::where('dates', '=', date('Y-m-d'))->where('type', '=', 'mobilecode')->where('value1', '=', session('mobile'))->orderBy('id', 'desc')->paginate(6);
                if (count($syslog)>=5){
                    return 'maxdate';
                }else{

                    session()->put('code', $code = rand(1000,9999));
                    $status = json_decode($smsSubmail->send_message(session('mobile'),$code,'18392','KtEIn1'),true);
                    if ($status['status']=='success'){
                        Syslog::create([
                            'dates' => date('Y-m-d'),
                            'type' => 'mobilecode',
                            'value1' => session('mobile'),
                        ]);
                        return $status['status'];
                    }else{
                        return 'err3';
                    }
                }

            }else{
                return 'error';
            }
        }
    }

    public function update(Request $request,User $user)
    {

    }
    public function destroy(User $user)
    {
        //$user->delete();
    }
    /**
     * 以下是通过手机找回密码的操作
     */
    //发送手机验证码，确认身份
    public function mobile_store_passworld(Request $request,SmsSubmail $smsSubmail)
    {

        if ($request->isMethod('POST')){

            if (!session()->put('code')){
                $this->validate($request,[
                    'mobile' => 'required|min:11|mobile',
                    'captcha' => 'required|captcha'
                ]);

                //判断用户是否存在
                $user = User::where('mobile', $request->mobile)->first();
                if ($user==NULL){
                    session()->flash('danger', '该手机号码不存在！请核对！');
                    return back();
                }

//                var_dump($user);

                //发送重置密码 验证短信
                $syslog = Syslog::where('dates', '=', date('Y-m-d'))->where('type', '=', 'mobilecode')->where('value1', '=', $request->mobile)->orderBy('id', 'desc')->paginate(6);
                if (count($syslog)>=5){
                    session()->flash('danger', '短信发送超过了每天发送的最大次数！');
                    return back();
                }else{
                    session()->put('code', $code = rand(1000,9999));
                    $status = json_decode($smsSubmail->send_message($request->mobile,$code,'18392','PHV3L4'),true);
                    if ($status['status']=='success'){
                        Syslog::create([
                            'dates' => date('Y-m-d'),
                            'type' => 'mobilecode',
                            'value1' => $request->mobile,
                        ]);
                        session()->put('mobile', $request->mobile);
                    }else{
                        session()->flash('danger', '系统短信发送失败！请稍后再试或联系我们！');
                        return back();
                    }
                }
            }
            return view('user.mobile_store_passworld_two');
        }
        session()->pull('code','default');
        return view('user.mobile_store_passworld_one');
    }
    //验证手机验证码身份，发送重置密码
    public function mobile_to_code(Request $request,SmsSubmail $smsSubmail)
    {
        if ($request->isMethod('POST') and session()->get('mobile') and session()->get('code'))
        {
            if(session()->get('code')!=$request->smscode){
//                echo '手机验证码错误！请重新操作或联系我们！';die();
                session()->flash('danger', '手机验证码错误！请重新操作或联系我们！');
                return back();
            }
            $syslog = Syslog::where('dates', '=', date('Y-m-d'))->where('type', '=', 'mobilecode')->where('value1', '=', $request->mobile)->orderBy('id', 'desc')->paginate(6);
            if (count($syslog)>=8){
                session()->flash('danger', '短信发送超过了每天发送的最大次数！');
                return back();
            }else{
                session()->put('code', $code = rand(100000,999999));
//                echo $code;
//                echo $code = str_random(6);
                $status = json_decode($smsSubmail->send_message(session()->get('mobile'),"$code",'18392','BRmEl3'),true);

                if ($status['status']=='success'){
                    //发送成功
                    Syslog::create([
                        'dates' => date('Y-m-d'),
                        'type' => 'mobilecode',
                        'value1' => session('mobile'),
                    ]);
                    $bool = DB::table('users')->where('mobile',session('mobile'))->update(['password'=>Hash::make($code)]);
                    if ($bool){
                        $request->session()->flash('success', '修改成功！请采用新密码登录！');
                        return redirect()->route('Login');
                    }
//                    return 'ok'.$status['status'];
                }else{
//                    print_r($status);
//                    echo '系统短信发送失败！请重新操作或联系我们！';die();
                    session()->flash('danger', '系统短信发送失败！请重新操作或联系我们！');
                        return back();
                }
            }
        }
    }

    public function passworld_update()
    {
        if(!is_object(auth()->user())){return redirect(route('Login'));}
        return view('user.passworld_update',[
            'now_link' => 'index',
            'title' => '修改密码',
        ]);
    }
    /*
     * 修改密码
     */
    public function passworld_update_store(Request $request)
    {
        if(!is_object(auth()->user())){return redirect(route('Login'));}

        if ($request->isMethod('PUT')){
//            echo $id = $request->get('id');
            $this->validate($request,[
                'password' => 'required|min:6|confirmed'
            ]);

            $users = User::find($request->get('id'));
//            echo $request->get('password');

//            dd($users);exit;
            if (Hash::check($request->get('passwordo'), $users->password)){
//                return DB::table('users')->where('id',$id)->increment('password',Hash::make($request->get('password')));
                $bool = DB::table('users')->where('id',$request->get('id'))->update(['password'=>Hash::make($request->get('password'))]);
                if ($bool){
                    $request->session()->flash('success', '修改成功！下次登录请采用新密码！');
                    return redirect()->route('Passworld_update');
                }
            }else{
                $request->session()->flash('danger', '旧密码错误！');
                return redirect()->route('Passworld_update');
            }

        }
    }
}
